#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Web配置文件
存储Web界面设置的推送配置
"""

import json
import os
from datetime import datetime

# 配置文件路径
CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'web_config.json')

class WebConfig:
    def __init__(self):
        # 初始化默认配置
        self.default_config = {
            'wechat_push_enabled': False,  # 默认关闭推送
            'target_groups': []  # 默认没有推送群
        }
        self.config = self.load_config()
    
    def load_config(self):
        """从配置文件加载配置"""
        try:
            if os.path.exists(CONFIG_FILE):
                with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                    return json.load(f)
            else:
                # 如果文件不存在，返回默认配置并保存
                config = self.default_config.copy()
                self.save_config(config)
                return config
        except Exception as e:
            print(f"加载Web配置失败: {e}")
            return self.default_config.copy()
    
    def save_config(self, config=None):
        """保存配置到文件"""
        try:
            if config is None:
                config = self.config
            
            # 确保配置目录存在
            os.makedirs(os.path.dirname(CONFIG_FILE), exist_ok=True)
            
            # 添加保存时间
            config['last_updated'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            
            with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存Web配置失败: {e}")
            return False
    
    def get_wechat_push_enabled(self):
        """获取微信推送是否启用"""
        return self.config.get('wechat_push_enabled', False)
    
    def set_wechat_push_enabled(self, enabled):
        """设置微信推送是否启用"""
        self.config['wechat_push_enabled'] = enabled
        return self.save_config()
    
    def get_target_groups(self):
        """获取目标推送群列表"""
        return self.config.get('target_groups', [])
    
    def set_target_groups(self, groups):
        """设置目标推送群列表"""
        self.config['target_groups'] = groups
        return self.save_config()
    
    def add_target_group(self, group_name):
        """添加一个目标推送群"""
        if group_name not in self.config['target_groups']:
            self.config['target_groups'].append(group_name)
            return self.save_config()
        return True
    
    def remove_target_group(self, group_name):
        """移除一个目标推送群"""
        if group_name in self.config['target_groups']:
            self.config['target_groups'].remove(group_name)
            return self.save_config()
        return True
    
    def get_full_config(self):
        """获取完整配置"""
        return self.config

# 创建全局配置实例
web_config = WebConfig()